import base64
import hashlib
import hmac
import time
import urllib

import requests

DingTalkNotifyUrl = "https://oapi.dingtalk.com/robot/send?" \
                    "access_token=55c7b6a589f919505c860d19c831ea983dd807f45a5f0814c41b1804aca91d10"

DingTalkNotifyGroupSecret = "SECbee5ba188d355aad73f2581e4dd43421862a619415185e354b1f9cf9b7b4aa0b"


class DingTalkNotifyUtil(object):
    def __init__(self, notify_url: str = DingTalkNotifyUrl):
        self.notify_url = notify_url
        self.msg_type = "markdown"

    @staticmethod
    def prepare_ding_talk_sign_str():
        timestamp = str(round(time.time() * 1000))
        secret = DingTalkNotifyGroupSecret
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        return f"&timestamp={timestamp}&sign={sign}"

    def notify(self, title: str, text: str):
        data = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": f"### __{title}__ \n  {text}"
            }
        }
        sign_str = self.prepare_ding_talk_sign_str()
        resp = requests.post(url=self.notify_url + sign_str, json=data, verify=False)
        return resp.text


def notify(_body_json):
    _alerts_ = _body_json['alerts']
    _summary = _body_json['commonAnnotations']['summary']

    _body = ""
    for _alert in _alerts_:
        _labels_ = _alert['labels']
        _instance = _labels_['instance']
        _job = _labels_['job']
        _alert_name = _labels_['alertname']
        _body += f'- __{_job}__ [{_instance}](http://{_instance}) \n > alert name : {_alert_name} \n'

    process = DingTalkNotifyUtil()
    return process.notify(title=_summary, text=_body)


def notify_by_ding_talk(title: str, text: str):
    process = DingTalkNotifyUtil()
    return process.notify(title, text)


def ding_talk_notify_demo():
    process = DingTalkNotifyUtil()
    process.notify("标题", "python 发送 钉钉通知消息 正文内容")


if __name__ == "__main__":
    ding_talk_notify_demo()
